package com.orm.analysis.action;

import com.opensymphony.xwork2.ActionContext;
import com.orm.analysis.model.ContactInfo;
import com.orm.analysis.model.Customer;
import com.orm.analysis.service.GenericService;
import java.util.List;
import java.util.Map;


public class CustomerAction extends FrontendAction  {

    private GenericService<Customer> service;
    private GenericService<ContactInfo> contactInfoService;
    private Customer customer;
    private List<ContactInfo> contactInfoList;
    private List<Customer> customers;


    public CustomerAction(GenericService<Customer> service,GenericService<ContactInfo> contactInfoService) {
        this.service = service;
        this.contactInfoService = contactInfoService;
    }

    public String getAllCustomers() {
        customers = service.list(page, size);
        return SUCCESS;
    }

     public String list() {
        customers = service.list(page, size);
        return SUCCESS;
    }

    public String setUpForInsertOrUpdate(){
        prep();
    		if (customer != null && customer.getId() != null) {
                customer = service.getById (customer.getId());
    		}
    		return "success";
    	}


        public String insertOrUpdate(){

            prep();

        	if(!validationSuccessful()){
        		return "input";
        	}else{
        		if (customer.getId()  == null) {
                    service.create(customer);
        		} else {
                    service.update(customer);
        		}

        	}
        	return "success";
        }


    private void prep() {
        contactInfoList = contactInfoService.list(page, size);
		Map session = ActionContext.getContext().getSession();
		session.put("contactInfoList", contactInfoList);
	}


    public String update() {
        service.update(customer);
        return SUCCESS;
    }

    public String create() {
        service.create(customer);
        return SUCCESS;
    }

    public String delete() {
        service.delete(customer.getId());
        return SUCCESS;
    }


    private boolean validationSuccessful(){
       	if(customer.getFirstName()==null||customer.getFirstName().trim().length()<1){
       		addActionMessage("FirstName is required");
       	}
       	if(customer.getLastName()==null||customer.getLastName().trim().length()<1){
       		addActionMessage("LastName is required");
       	}

       	if(this.hasActionMessages()){
       		return false;
       	}else{
       		return true;
       	}


       }


    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }
}
